<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../../lib/layui-v2.5.6/layui/css/layui.css">
    <!-- <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" type="text/css"> -->
</head>
<style>
    .layui-form-label {
        padding-left: 0px;
        width: 60px;
    }

    .layui-form-radio {
        margin-right: 0px;
        padding-right: 5px;
    }

    .input-card {
        display: flex;
        flex-direction: column;
        min-width: 0;
        word-wrap: break-word;
        background-color: #fff;
        background-clip: border-box;
        border-radius: .25rem;
        border-width: 0;
        border-radius: 0.4rem;
        box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
        position: fixed;
        bottom: 1rem;
        right: 1rem;
        -ms-flex: 1 1 auto;
        flex: 1 1 auto;
        padding: 0.75rem 1.25rem;
    }


    .input-item {
        position: relative;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-wrap: wrap;
        flex-wrap: wrap;
        -ms-flex-align: center;
        align-items: center;
        width: 100%;
        height: 3rem;
    }
</style>

<body>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md6" style="height: 93px;">
                <div class="layui-card">
                    <div class="layui-card-body  " style="height: 58px;">

                        <form id="form" class="layui-form" action="">
                            <div class="layui-form-item">
                                <label class="layui-form-label">车辆选择:</label>
                                <div class="layui-input-inline">
                                    <select id="carSel" lay-filter="carSel" name="quiz1">
                                    </select>
                                </div>
                            </div>
                        </form>

                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-body ">
                        <form id="form" class="layui-form" action="">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">图标尺寸</label>
                                    <div class="layui-input-inline" style="width: 160px;">
                                        <input type="radio" lay-filter="iconRadio" name="iconSize" value="carBig"
                                            title="大">
                                        <input type="radio" lay-filter="iconRadio" name="iconSize" value="carMiddle"
                                            title="中">
                                        <input type="radio" lay-filter="iconRadio" name="iconSize" value="carLittle"
                                            title="小" checked>
                                    </div>
                                </div>

                                <div class="layui-inline">
                                    <label class="layui-form-label">跟踪车辆</label>
                                    <div class="layui-input-inline" style="width: 60px;">
                                        <input type="checkbox" lay-filter="followCar" lay-text="开启|关闭" checked
                                            name="switch" lay-skin="switch">
                                    </div>
                                </div>

                                <div class="layui-inline">
                                    <label class="layui-form-label">实时轨迹</label>
                                    <div class="layui-input-inline" style="width: 60px;">
                                        <input type="checkbox" lay-filter="trackCar" lay-text="开启|关闭" name="switch"
                                            checked lay-skin="switch">
                                    </div>
                                </div>

                                <div class="layui-inline">
                                    <label class="layui-form-label">电子围栏</label>
                                    <div class="layui-input-inline" style="width: 60px;">
                                        <input type="checkbox" lay-filter="electronicFence" lay-text="开启|关闭"
                                            name="switch" lay-skin="switch">
                                    </div>
                                </div>
                            </div>

                        </form>
                    </div>
                </div>
            </div>

            <div class="layui-col-md12">
                <div class="layui-card" style="height: 100%;">
                    <div class="layui-card-body" style="height:1000px">
                        <div id="mapDiv" style="height: 100%;"></div>
                        <div class="input-card" id="toolWin" style='display:none;width: 15rem;'>
                            <form id="form" class="layui-form" lay-filter="tool" action="#">
                                <div class="layui-form-item">
                                    <div class="layui-inline" lay-filter="shapeRadioDiv">
                                        <input type="radio" lay-filter="shapeRadio" name="figureShape" value="polygon"
                                            checked title="多边形">
                                        <input type="radio" lay-filter="shapeRadio" name="figureShape" value="rectangle"
                                            title="矩形">
                                        <input type="radio" lay-filter="shapeRadio" name="figureShape" value="circle"
                                            title="圆形">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <button id="clearLastOneBtn"
                                            class="layui-btn layui-btn-primary layui-btn-sm">清除上一个</button>
                                        <button id="clearAllBtn"
                                            class="layui-btn layui-btn-normal  layui-btn-sm">全部清除</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>
</body>
<script src="../../lib/layui-v2.5.6/layui/layui.js"></script>
<script type="text/javascript"
    src="https://webapi.amap.com/maps?v=1.4.15&key=eaaf6657a53a8df63c30e059316b6982&plugin=AMap.MouseTool"></script>
<script>
    layui.use(['form', 'jquery', 'layedit', 'laydate', 'element'], function () {
        form = layui.form;
        $ = layui.$;
        var timerArr = [];
        var pointLinArr = [];

        var map = "";
        var latitude = "";
        var longitude = "";

        var carId = "";
        var markerIcon = "";
        var offset = "";
        var isFollowCar = true;
        var isTrackCar = true;
        var polyline = "";
        var marker = "";
        var overlays = []; //用来存放手动画出来的覆盖物
        var fenceAlarm = {
            "isOpen": false,
            "carStatus": false,
            "isFirst": true
        }
        $(function () {
            getCarList();
            initMap();
            carId = $("#carSel").val();
            getMakerIcon("carLittle")
            makePoint();
            //监听切换车辆
            form.on('select(carSel)', function (data) {
                pointLinArr = [];
                carId = data.value;
                //移除定时器
                for (var k = 0; k < timerArr.length; k++) {
                    clearInterval(timerArr[k]);
                }
                makePoint();
            });
            //监听图标尺寸
            form.on('radio(iconRadio)', function (data) {
                getMakerIcon(data.value)
                marker.setIcon(image)
                marker.setOffset(offset)
            });
            //监听是否跟踪车辆
            form.on('switch(followCar)', function (data) {
                isFollowCar = data.elem.checked
            });
            //监听是否开启轨迹线
            form.on('switch(trackCar)', function (data) {
                pointLinArr = [];
                isTrackCar = data.elem.checked
            });
            //监听是否开启电子围栏
            form.on('switch(electronicFence)', function (data) {
                if (data.elem.checked) {
                    $("#toolWin").css("display", "inline");
                    draw("polygon")
                    form.val('tool', { "figureShape": "polygon" });
                    fenceAlarm.isOpen = true
                } else {
                    $("#toolWin").css("display", "none");
                    mouseTool.close(true);
                    overlays = []
                    fenceAlarm = {
                        "isOpen": false,
                        "carStatus": false,
                        "isFirst": true
                    }
                }
            });
            //监听图标尺寸
            form.on('radio(shapeRadio)', function (data) {
                draw(data.value)
            });

            form.on('submit(tool)', function (data) {
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
        })
        //地图初始化
        function initMap() {
            map = new AMap.Map('mapDiv', {
                zoom: 11,//级别
                center: [123.435, 41.6986],//中心点坐标
                resizeEnable: true //是否监控地图容器尺寸变化
            });

            mouseTool = new AMap.MouseTool(map);
            mouseTool.on('draw', function (e) {
                overlays.push(e.obj);
            })
        }

        //获取车辆列表
        function getCarList() {
            $.ajax({
                url: "http://device-dev.horus.net.cn/api/vehicle/getVehicle",
                data: {
                    "Authorization": "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ"
                },
                type: "get",
                async: false,
                success: function (res) {
                    carList = res.content;
                    var opt = "";
                    for (var i = 0; i < carList.length; i++) {
                        opt += "<option value='" + carList[i].id + "'";
                        if (i == 0) {
                            opt += "selected "
                        }
                        opt += " >" + carList[i].number + "</option>";
                    }
                    $("#carSel").html(opt);
                    form.render('select')
                }
            })
        }

        //根据车辆id获取最后坐标点
        function getLastLocationByCarId(carId) {
            $.ajax({
                url: "http://device-dev.horus.net.cn/api/vehicle/getLastPosition",
                data: {
                    "Authorization": "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ",
                    "vid": carId
                },
                type: "get",
                async: false,
                success: function (res) {
                    latitude = res.content.latitude;
                    longitude = res.content.longitude;
                    console.log(res.content)
                }
            })
        }




        //在地图上描绘坐标点
        function makePoint() {
            var j = 0.0000;//模拟运动,开发中使用.上线前需要删掉
            var timer = setInterval(
                function () {
                    //获取最后坐标点
                    getLastLocationByCarId(carId);
                    //获取新的坐标点并加载到地图上
                    //var lastLocation = new AMap.LngLat(longitude,latitude);
                    var lastLocation = new AMap.LngLat(longitude + 0.0001 * j, latitude + 0.0001 * j);
                    //map.setCenter(lastLocation); 
                    //判断地图上是否有坐标点,如果有,则直接改变点的坐标,如果没有,则生成一个新的坐标点
                    if (marker != "" && marker != undefined) {
                        //当浏览器不在当前页面时,小汽车会停止移动.判断小汽车的点和最后坐标点的距离
                        if (getV(latitude + 0.0001 * j, longitude + 0.0001 * j, marker.getPosition().lat, marker.getPosition().lng) > 50) {
                            marker.setPosition(lastLocation) //跳转到坐标点
                        } else {
                            marker.moveTo(lastLocation, 80)//移动到坐标点,第二个参数为速度,单位km/h
                        }
                    } else {
                        marker = new AMap.Marker({
                            icon: image,
                            position: lastLocation,
                            offset: offset,
                            autoRotation: true
                        });
                        marker.setMap(map);
                    }
                    //是否地图重置中心点,即跟随目标
                    if (isFollowCar) {
                        map.panTo(lastLocation);
                    }
                    //是否生成实时轨迹 
                    if (isTrackCar) {
                        pointLinArr.push(lastLocation);
                    }
                    //这样做是为了轨迹线是实时的, 有且只有一根轨迹线
                    if (polyline != "" && polyline != undefined) {
                        polyline.setPath(pointLinArr)

                    } else {
                        polyline = new AMap.Polyline({
                            path: pointLinArr,
                            strokeWeight: 8,
                            strokeOpacity: 0.8,
                            strokeColor: '#0091ea',
                            showDir: true,
                            lineJoin: 'round',
                            lineCap: 'round', // 折线拐点连接处样式
                        });

                        map.add(polyline);
                    }

                    if (fenceAlarm.isOpen) {
                        for (var i = 0; i < overlays.length; i++) {
                            console.log(overlays[i].getPath())
                            var isPointInRing = AMap.GeometryUtil.isPointInRing(lastLocation, overlays[i].getPath());
                            if (fenceAlarm.isFirst) {
                                fenceAlarm.carStatus = isPointInRing
                                fenceAlarm.isFirst = false
                            }
                            if (fenceAlarm.carStatus != isPointInRing) {
                                if (isPointInRing) {
                                    alert("进圈了")
                                } else {
                                    alert("出圈了")
                                }
                                fenceAlarm.carStatus = isPointInRing
                            }
                        }
                    }





                    j++
                    console.log(overlays)
                },
                1000);
            timerArr.push(timer)

        }

        //画覆盖物
        function draw(type) {
            switch (type) {
                case 'polygon': {
                    mouseTool.polygon({
                        fillColor: '#00b0ff',
                        strokeColor: '#80d8ff'
                        //同Polygon的Option设置
                    });
                    break;
                }
                case 'rectangle': {
                    mouseTool.rectangle({
                        fillColor: '#00b0ff',
                        strokeColor: '#80d8ff'
                        //同Polygon的Option设置
                    });
                    break;
                }
                case 'circle': {
                    mouseTool.circle({
                        fillColor: '#00b0ff',
                        strokeColor: '#80d8ff'
                        //同Circle的Option设置
                    });
                    break;
                }
            }
        }


        $('#clearLastOneBtn').on('click', function () {
            map.remove(overlays[overlays.length - 1])
            overlays.pop()
            if (overlays.length == 0) {
                fenceAlarm = {
                    "carStatus": false,
                    "isFirst": true
                }
            }
        });

        $('#clearAllBtn').on('click', function () {
            map.remove(overlays)
            overlays = []
            fenceAlarm = {
                "carStatus": false,
                "isFirst": true
            }
        });






        //车辆图标
        function getMakerIcon(iconName) {
            var size = "";

            if (iconName == "carBig") {
                size = new AMap.Size(112, 45);//图片大小
                offset = new AMap.Pixel(-56, -23)
            } else if (iconName == "carMiddle") {
                size = new AMap.Size(84, 34);//图片大小
                offset = new AMap.Pixel(-42, -17)
            } else if (iconName == "carLittle") {
                size = new AMap.Size(56, 22);//图片大小
                offset = new AMap.Pixel(-28, -11)
            }
            // 图标尺寸
            //size: size,
            // 图标的取图地址
            image = "../../lib/image/" + iconName + ".png"
            //imgageSze:size
        }

        //已知两点获取距离
        function getV(lng1, lat1, lng2, lat2) {
            var radLat1 = lat1 * Math.PI / 180.0;
            var radLat2 = lat2 * Math.PI / 180.0;
            var a = radLat1 - radLat2;
            var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378.137;// EARTH_RADIUS;
            s = Math.round(s * 10000) / 10;//单位为m
            //s = Math.round(s * 10000) / 10000;//单位为km
            return s;
        }




    })
</script>

</html>